const express = require("express");
const router = express.Router();
const { Article } = require("../model");
const acticleValidate = require("../validator/article");
const auth = require("../middleware/auth");
//获取文章列表
router.get("/", async (req, res, next) => {
  try {
    const { offet, limit } = req.query;
    const article = await Article.countDocuments();
    const articles = await Article.find()
      .skip(parseInt(offet))
      .limit(parseInt(limit))
      .sort({
        createAt: 1,
      });
    res.send({
      articles,
      article,
    });
  } catch (error) {
    next(error);
  }
});
//获取用户关注文章列表
router.get("/feed", async (req, res, next) => {
  try {
    res.send("ok");
  } catch (error) {
    next(error);
  }
});

//获取文章
router.get("/:slug", async (req, res, next) => {
  try {
    const article = await Article.findById(req.params.slug);
    if (!article) {
      return res.status(404).end();
    }
    res.send({
      article,
    });
  } catch (error) {
    next(error);
  }
});
//创建文章
router.post("/", acticleValidate.createArticle, async (req, res, next) => {
  try {
    const article = new Article(req.body.article);
    console.log(req.user);
    //  article.author=req.body.user._id
    //  article.populate('author').execPopulate()
    await article.save();
    res.send({
      article,
    });
  } catch (error) {
    next(error);
  }
});
//更新文章
router.put("/:id", auth, async (req, res, next) => {
  try {
    const id = req.params.id;
    const article = await Article.findById(id.toString());
    if (!article) {
      res.status(404).end();
    }
    res.send("ok");
  } catch (error) {
    next(error);
  }
});

//删除文章
router.delete("/:slug", async (req, res, next) => {
  try {
    res.send("ok");
  } catch (error) {
    next(error);
  }
});
//添加文章评论

router.post("/:slug:comments", async (req, res, next) => {
  try {
    res.send("ok");
  } catch (error) {
    next(error);
  }
});
//获取文章评论
router.get("/:slug:comments", async (req, res, next) => {
  try {
    res.send("ok");
  } catch (error) {
    next(error);
  }
});

//删除文章评论
router.get("/:slug:comments/:id", async (req, res, next) => {
  try {
    res.send("ok");
  } catch (error) {
    next(error);
  }
});

module.exports = router;
